package sword.T37;

import util.TreeNode;

/**
 * @Author: 18362
 * @Create: 2022-04-08 15:28:17 星期五
 */

public class Codec {

    private String sep = ",";
    private String nul = "#";
    private int idx = 0;

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        tranverse(root, sb);
        return sb.toString();
    }

    public void tranverse(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append(nul).append(sep);
            return;
        }
        sb.append(root.val).append(sep);
        tranverse(root.left, sb);
        tranverse(root.right, sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] ss = data.split(",");
        return deserialize(ss);
    }

    public TreeNode deserialize(String[] data) {
        if (idx >= data.length || data[idx].equals(nul)) {
            idx++;
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(data[idx++]));
        root.left = deserialize(data);
        root.right = deserialize(data);
        return root;
    }
}